rm(list=ls(all=TRUE))

path <- "" #here you need to adjust the path macro to the place on your computer
setwd(path)

# install.packages("tidyverse", "Hmisc", "ggrepel")

library(haven)
library(dplyr)
library(ggplot2)
library(Hmisc)
library(ggrepel)
library(xlsx)
library(cowplot)

# the original data file will be freely available online (http://www.poldem.eu/). For now, please ask for the latest version from the authors.

dat <- read_dta(paste0(path, "\\chapter_wide.dta"))

##################################
###### Figure 3, appendix C ######
##################################

dat$iso2code <- as_factor(dat$iso2code)
dat$country <- as_factor(dat$country)

# adjusting the sample, dropping parties which have not sponsored 
# protests and cabinets under which no protest has happened.

table(dat$country)
length(unique(dat$country))


# low and high contexts

cntry_lev <-  dat %>% 
  group_by(iso2code) %>%
  summarise_at(vars(aglpopw_event, aglpopw_part_all, wparties), funs(sum(., na.rm=TRUE))) %>% 
  mutate(prt_share = wparties*100/aglpopw_event) %>% 
  select(iso2code, prt_share, aglpopw_event, aglpopw_part_all) %>% 
  ungroup(.) %>% 
  mutate(diff_threshold=median(prt_share)) %>% 
  mutate(diff_dummy=ifelse(prt_share<=diff_threshold, 1, 0)) %>% 
  arrange(prt_share) 

# differentiated countries

nodiff.cntry <- c("BG", "CY", "CZ", "EE", "DE", "HU", "IS", "LV", "LT", "SK", "CH")
diff.cntry <- c("AT", "BE", "DK", "FI", "FR", "GR", "IE", "IT", "LU", "MT", "NL", "NO", "PL", "PT", "RO", "SI", "ES", "SE", "UK")

cntry_lev$prt_share_cat[as.character(cntry_lev$iso2code) %in% diff.cntry] <- 0
cntry_lev$prt_share_cat[as.character(cntry_lev$iso2code) %in% nodiff.cntry] <- 1
cntry_lev$prt_share_cat <- as.factor(cntry_lev$prt_share_cat)
cntry_lev$prt_share_cat <- relevel(cntry_lev$prt_share_cat, "0")

table(cntry_lev$prt_share_cat)
cor(as.numeric(cntry_lev$prt_share_cat), as.numeric(cntry_lev$diff_dummy))

dat_upper_lev_cat <- subset(cntry_lev, select=c("iso2code",
                                               "prt_share",
                                               "prt_share_cat"))
dat <- merge(dat, dat_upper_lev_cat)
rm(dat_upper_lev_cat, cntry_lev)

table(dat$prt_share_cat)

# additional variables

dat$economic <- as.factor(dat$economic)
dat$NSM <- as.factor(dat$NSM)
dat$ANSM <- as.factor(dat$ANSM)
dat$political <- as.factor(dat$political)
dat$unions <- as.factor(dat$unions)
dat$otherorg <- as.factor(dat$otherorg)
dat$petition[grepl("petition", dat$action)] <- 1
dat$petition[is.na(dat$petition)] <- 0
dat$petition <- as.factor(dat$petition)
dat$strike[grepl("strike", dat$action)] <- 1
dat$strike[is.na(dat$strike)] <- 0
dat$strike <- as.factor(dat$strike)
dat$confrontation[grepl("blockade", dat$action)] <- 1
dat$confrontation[is.na(dat$confrontation)] <- 0
dat$confrontation <- as.factor(dat$confrontation)
dat$violence[grepl("violent", dat$action)] <- 1
dat$violence[is.na(dat$violence)] <- 0
dat$violence <- as.factor(dat$violence)
dat$demo[grepl("demonstration", dat$action)] <- 1
dat$demo[is.na(dat$demo)] <- 0
dat$demo <- as.factor(dat$demo)
dat$aft_elect_prt <- as.factor(dat$aft_elect_prt)
dat$bef_elect_prt <- as.factor(dat$bef_elect_prt)
dat$ctr_year <- as.factor(dat$ctr_year)

dat$cultural[dat$NSM==1 | dat$ANSM==1] <- 1
dat$cultural[is.na(dat$cultural)] <- 0
dat$cultural <- as.factor(dat$cultural)
table(dat$cultural)

dat$culteco[dat$cultural==1 | dat$economic==1] <- 1
dat$culteco[is.na(dat$culteco)] <- 0
dat$culteco <- as.factor(dat$culteco)

dat$big_event <- as.factor(dat$big_event)
dat$coorg[dat$unions==1 | dat$otherorg==1] <- 1
dat$coorg[is.na(dat$coorg)] <- 0

dat$violconf[dat$violence == 1 | dat$confrontation == 1] <- 1
dat$violconf[is.na(dat$violconf)] <- 0


# tables with shares

# economic

hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(economic)) %>% 
  group_by(prt_share_cat, economic) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(economic)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(economic==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- cbind("economic", hdat3)
rm(list=ls(pattern="hdat"))

#cultural

hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(cultural)) %>% 
  group_by(prt_share_cat, cultural) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(cultural)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(cultural==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- rbind(table, cbind("cultural", hdat3))
rm(list=ls(pattern="hdat"))

#demo

hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(demo)) %>% 
  group_by(prt_share_cat, demo) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(demo)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(demo==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- rbind(table, cbind("demo", hdat3))
rm(list=ls(pattern="hdat"))

#coorg

hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(coorg)) %>% 
  group_by(prt_share_cat, coorg) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(coorg)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(coorg==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- rbind(table, cbind("coorg", hdat3))
rm(list=ls(pattern="hdat"))

#big_event

hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(big_event)) %>% 
  group_by(prt_share_cat, big_event) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(big_event)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(big_event==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- rbind(table, cbind("big_event", hdat3))
rm(list=ls(pattern="hdat"))

#violconf


hdat3.1 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(violconf)) %>% 
  group_by(prt_share_cat, violconf) %>% 
  summarise_at(vars(wparties), funs(sum(., na.rm=TRUE)))
hdat3.2 <- dat %>%
  filter(!is.na(prt_share_cat) & !is.na(violconf)) %>% 
  group_by(prt_share_cat) %>% 
  summarise(group_tot=sum(wparties, na.rm=TRUE))
hdat3 <- merge(hdat3.1, hdat3.2)
hdat3 <- hdat3 %>% 
  mutate(sh= case_when(violconf==1 ~ wparties*100/group_tot)) %>% 
  select(prt_share_cat, sh) %>% 
  filter(complete.cases(.))
hdat3 <- t(hdat3[,2])
colnames(hdat3) <- c("low pp", "high pp")
print(hdat3)
table <- rbind(table, cbind("violconf", hdat3))
rm(list=ls(pattern="hdat"))

# arrange table

colnames(table)[1] <- "name"
table <- as.data.frame(table)

table[,-1] <- sapply(table[,-1],as.character)
table[,-1] <- sapply(table[,-1],as.numeric)

in_paper_r <- c("economic", "cultural", "violconf",
                "demo", "coorg", "big_event") #,"culteco", "political"

table <- subset(table, name %in% in_paper_r, select=c("name", "low pp", "high pp"))

table <- reshape2::melt(table, id.vars="name")

table$name <- as.character(table$name)
table$name[table$name=="economic"] <- "Economic"
table$name[table$name=="cultural"] <- "Cultural"
table$name[table$name=="culteco"] <- "Cultural & Economic"
table$name[table$name=="political"] <- "Political"
table$name[table$name=="demo"] <- "Demonstration"
table$name[table$name=="coorg"] <- "Co-organized"
table$name[table$name=="big_event"] <- "Big Events"
table$name[table$name=="violconf"] <- "Violent & Confont."

table$name <- factor(table$name, levels = c("Economic", 
  "Cultural", "Cultural & Economic", "Political", "Demonstration", "Violent & Confont.","Co-organized", "Big Events"))

table$variable <- as.character(table$variable)
table$variable[grepl("low", table$variable)] <- "low"
table$variable[grepl("high", table$variable)] <- "high"

table$row <- as.numeric(0)
first_row <- c("Economic", "Cultural", "Cultural & Economic", "Political", "Demonstration")
table$row[table$name %in% first_row] <- 1

table <- table %>% 
group_by(row) %>%
  mutate(max.height = max(value)) %>%
  ungroup()


margins <- c(5.5, 5.5, 0, 11)

first_row <- ggplot(table[table$row==1,], aes(x=variable, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  facet_wrap(~name,nrow=1) +
  xlab("") + ylab("") + # 
  scale_x_discrete(labels=c("low" = "High Diff.",
                            "high" = "Low Diff.")) +
  scale_fill_manual(values=c("#2a2b2d", "#7f8082")) +
  guides(fill=FALSE) +
  theme_bw() + scale_y_continuous(breaks=seq(0,75,15),
                                  limits = c(0,80)) +
  theme(plot.margin=margin(unit(margins, "points")))

second_row <- ggplot(table[table$row!=1,], aes(x=variable, y=value, fill=variable)) +
  geom_bar(stat="identity") +
  facet_wrap(~name,nrow=1) +
  xlab("") + ylab("") + 
  scale_x_discrete(labels=c("low" = "High Diff.",
                            "high" = "Low Diff.")) +
  scale_fill_manual(values=c("#2a2b2d", "#7f8082")) +
  guides(fill=FALSE) +
  theme_bw() + scale_y_continuous(breaks=seq(0,35,15),
                                  limits = c(0,35)) +
  theme(plot.margin=margin(unit(margins, "points")))

combined <- cowplot::plot_grid(first_row, second_row, nrow=2, label_y="Share in party protests (pp.)")

all <- combined + draw_label("Share in party protests (pp.)",
                      x = 0.05, y = 0.3, hjust = 0, vjust = 0,
                      angle=90, size=11)

ggsave(paste0(path, "\\evt_barplot_avg.eps"),
       plot=all, dpi=200, scale=0.6, width=8, height=7)

ggsave(paste0(path, "\\evt_barplot_avg.png"),
       plot=all, dpi=200, scale=0.6, width=8, height=7)


